package com.ithl.edumsm.controller;

import com.ithl.commonutils.R;
import com.ithl.edumsm.service.MsmService;
import com.ithl.edumsm.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author hl
 * @Data 2020/4/22
 */
@RequestMapping("/edumsm/operation")
@RestController
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        // 先从redis获取验证码，获取不到就直接返回
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(redisCode)) {
            return R.ok();
        }
        // 生产随机值，传递到阿里云
        String code = RandomUtils.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSuccess = msmService.sendMessage(param, phone);
        if (!isSuccess) {
            return R.error().message("短信发送失败");
        } else {
            // 发送成功 设置有效时间为5分钟 TODO
            redisTemplate.opsForValue().set(phone, code, 20, TimeUnit.MINUTES);
            return R.ok();
        }
    }
}
